package com.padakeji.android.lockscreen;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;


public class MainActivity extends Activity {

    private final int mRequestCode = 100;

    private ComponentName mComponentName;
    private DevicePolicyManager mDevicePolicyManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyDeviceAdminReceiver mDeviceAdminReceiver = new MyDeviceAdminReceiver();

        mComponentName = mDeviceAdminReceiver.getWho(this);
        mDevicePolicyManager = mDeviceAdminReceiver.getManager(this);

        if (mDevicePolicyManager.isAdminActive(mComponentName)) {
            doLockScreen();
        } else {
            startAddDeviceAdminActivity();
        }
    }


    private void doLockScreen() {
        mDevicePolicyManager.lockNow();
        finish();
    }

    private void startAddDeviceAdminActivity() {
        Intent i = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        i.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
        i.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "一键锁屏需要以下授权");
        startActivityForResult(i, mRequestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mRequestCode && resultCode == Activity.RESULT_OK) {
            doLockScreen();
        } else {
            startAddDeviceAdminActivity();
        }
    }

}
